<?php

// +---------------------------------------------------
// | Name：星空框架  四川大朵 订单处理api
// +---------------------------------------------------
// | Version： V5.0
// +---------------------------------------------------
// | Author: xkyinzhe <zhonghuaxinxing@sina.cn>
// +---------------------------------------------------
// | Time: 2021-05-11 11:23
// +---------------------------------------------------
declare(strict_types=1);

namespace app\api\controller\v1;

use app\common\common\IndexController;
use app\common\model\Address as AddressModel;
use app\common\model\Car as CarModel;
use app\common\model\Order as OrderModel;
use app\common\model\User as UserModel;
use app\common\model\SubOrder as SubOrderModel;
use app\common\model\GoodsOrder as GoodsOrderModel;
use app\common\model\RefundOrder as RefundOrderModel;
use app\common\model\Store as StoreModel;
use app\common\model\RefundReason as RefundReasonModel;
use app\common\model\Shipping as ShippingModel;
use app\common\controller\Unionpay;
use app\common\services\OrderServices;
use app\common\services\UserServices;
use app\common\services\Lock;
use app\common\services\Task;
use app\common\services\SendMsg;
use think\facade\Db;

/**
 * @xk 订单处理
 */
class Order extends IndexController
{
    /**
     * @xk 创建订单
     *
     * @method createOrder
     * @param  OrderModel    $orderModel                [description]
     * @param  CarModel      $carModel                  [description]
     * @param  UserModel     $userModel                 [description]
     * @param  AddressModel  $addressModel              [description]
     * @param  Lock          $lock                      [description]
     * @param  OrderServices $orderServices             [description]
     * @return [type]        [description]
     * @Time   2021-09-01
     * @City   青岛
     * @Author xkyinzhe      <zhonghuaxinxing@sina.cn>
     */
    public function createOrder(OrderModel $orderModel, CarModel $carModel, UserModel $userModel, AddressModel $addressModel, Lock $lock, OrderServices $orderServices, UserServices $userServices)
    {
        $param = request()->param();
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        Db::startTrans();
        $lock = (new Lock())->lock([$param['user_sn']], 6000);
        try {
            if (!$lock) {
                throw new \think\Exception("提交过于频繁，请稍后重试", 404);
            }
            // 开始进行订单各项数据的处理
            $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
            $address_id = isset($param['address_id']) ? $param['address_id'] : 0;
            $car_id = isset($param['car_id']) ? $param['car_id'] : '';
            $be_from = isset($param['be_from']) ? $param['be_from'] : 'H5'; // 下单来源
            // $ifshare = isset($param['ifshare'])?$param['ifshare']:0;
            // $l_user_sn = isset($param['l_user_sn'])?$param['l_user_sn']:'';
            $shipping_type = isset($param['shipping_type']) ? $param['shipping_type'] : '';
            $content = isset($param['content']) ? $param['content'] : '';
            $user_info = $userModel
                ->where([['user_sn', '=', $user_sn]])
                ->field('`status`,`is_bind`,`l_user_sn`,`tel`,`wechat_app_openId`')
                ->find();
            if (!$user_info) {
                $resultData['jumpUrl'] = 'login';
                throw new \think\Exception("您还没有登录，请先进行登录", 300);
            }
            $user_info = $user_info->toArray();
            if (1 != $user_info['status']) {
                throw new \think\Exception('账户已注销', 404);
            }
            if ($address_id <= 0) {
                throw new \think\Exception('请选择收货地址', 404);
            }
            // if ($user_info['l_user_sn'] && $user_info['l_user_sn'] > 0 && $ifshare) {
            //     throw new \think\Exception("您已经存在推荐人，不需要填写推荐信息", 404);
            // }
            // 开始验证商品信息是否准确 组合订单商品信息表
            $order_data = [];
            $result = $orderServices->createOrderData($car_id, $address_id, $user_sn, $be_from, $shipping_type, $user_info['l_user_sn']); // 组合订单数据
            // 保存订单
            $order_data = $result['order_data'];
            $order_data['content'] = $content;
            $order_res = $orderModel->create($order_data);
            $orderServices->syncSubOrder($order_res->order_id, $result['sub_order_data'], $content); // 同步子订单数据&&同步商品订单数据
            (new Lock())->unlock($lock);
            Db::commit();
            $result_code = 200;
            $result_msg = '订单提交成功';
            $resultData = ['type' => 'all', 'order_sn' => $order_data['order_sn'], 'need_pay' => $order_data['need_pay']];
            // 执行完毕 开始执行解锁
        } catch (\Exception $e) {
            (new Lock())->unlock($lock);
            $result_code = 404;
            if ($e->getCode() == 300) {
                $result_code = 300;
            }
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }

    /**
     * @xk 获取订单分类
     *
     * @method getOrderType
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-05-11T15:33:16+080
     */
    public function getOrderType()
    {
        $list = [
            ['id' => 'ALL', 'order_type_text' => '全部'],
            ['id' => 'WAITPAY', 'order_type_text' => '待付款'],
            ['id' => 'WAITSHIPPING', 'order_type_text' => '待收货'],
            // ['id' => 'WAITSURE', 'order_type_text' => '待自提'],
            ['id' => 'REFUND', 'order_type_text' => '退款/售后'],
        ];

        $code = 200;
        $msg = '请求成功';
        $result_code = 200;
        $result_msg = '加载成功';
        $resultData = [];
        $resultData['list'] = $list;
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }

    /**
     * @xk 获取订单列表
     *
     * @method getOrderList
     *
     * @param OrderModel $orderModel [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-05-11T15:51:24+080
     */
    public function getOrderList(OrderModel $orderModel, SubOrderModel $subOrderModel, goodsOrderModel $goodsOrderModel, UserModel $userModel)
    {
        $param = request()->param();
        $order_type = isset($param['order_type']) ? $param['order_type'] : 'ALL'; // 默认全部订单
        $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
        $keywords = isset($param['keywords']) ? $param['keywords'] : '';
        $limit = isset($param['limit']) ? (int)$param['limit'] : 10;
        $page = isset($param['page']) ? (int)$param['page'] : 0;
        $code = 200;
        $msg = '请求成功';
        if ('' == $user_sn) {
            $result_code = 404;
            $result_msg = '您还没有登录，请先进行登录';
            $this->result($code, $msg, $result_code, $result_msg);
        }
        $user_info = $userModel->where([['user_sn', '=', $user_sn]])->field('`status`,`is_bind`,`tel`')->find();
        if (!$user_info) {
            $result_code = 404;
            $result_msg = '您还没有登录，请先进行登录';
            $this->result($code, $msg, $result_code, $result_msg);
        }
        if (1 != $user_info['status']) {
            $result_code = 404;
            $result_msg = '账户已注销';
            $this->result($code, $msg, $result_code, $result_msg);
        }
        $condition = [];
        $condition[] = ['o.user_sn', '=', $user_sn];
        switch ($order_type) {
            case 'WAITPAY':
                $condition[] = ['o.status', 'in', '0'];
                $condition[] = ['o.pay_status', '=', 0]; // 待付款
                $condition[] = ['o.refund_status', '<>', 2];
                break;
            case 'WAITSHIPPING':
                $condition[] = ['o.status', 'in', '1,2'];
                // $condition[] = ['o.shipping_type','=',1]; // 并且配送方式选择自提
                $condition[] = ['o.refund_status', '<>', 2];
                break;
            case 'WAITSURE':
                $condition[] = ['o.status', '=', 2]; // 待收货状态
                // $condition[] = ['o.shipping_type','=',2]; // 并且配送方式选择自提
                $condition[] = ['o.refund_status', '<>', 2];
                break;
            case 'WAITCOMMON':
                $condition[] = ['o.status', '=', 3]; // 确认收货还未进行评价
                $condition[] = ['o.refund_status', '<>', 2];
                break;
            case 'REFUND':
                $condition[] = ['o.refund_status', '<>', 0];
                break;
            default:
                $condition[] = ['o.status', '<>', 0];
                break;
        }
        if ($keywords != '') {
            $order_sn_arr = [];
            $order_sn_arr = $goodsOrderModel->where([['goods_name|sub_order_sn|order_sn', 'like', '%' . $keywords . '%']])->column('sub_order_sn');
            $condition[] = ['sub_order_sn', 'in', $order_sn_arr];
            // $condition[] = ['o.order_sn|o.sub_order_sn|o.user_sn','like','%'.$keywords.'%'];
        }
        $code = 200;
        $msg = '请求成功';
        switch ($order_type) {
            case 'WAITPAY':
                $condition = [];
                $condition[] = ['o.user_sn', '=', $user_sn];
                $condition[] = ['o.status', '=', 0];
                $result_count = $orderModel->alias('o')->where($condition)->count();
                if ($result_count <= ($page - 1) * $limit) {
                    $result_code = 203;
                    $result_msg = '没有更多数据了！';
                    $resultData = [];
                    $resultData['list'] = [];
                    $resultData['page'] = $page;
                    $this->result($code, $msg, $result_code, $result_msg, $resultData, $result_count);
                    exit();
                }
                $list = $orderModel
                    ->alias('o')
                    ->with(['orderGoods'])
                    ->where($condition)
                    ->field('o.`order_id`,o.`order_sn`,o.`status`,o.`status` as status_txt,o.`need_pay`,o.`pay_status`')
                    ->withAttr('status_txt', function ($value, $data) {
                        return '待付款';
                    })
                    ->page($page, $limit)
                    ->order('o.create_time desc')
                    ->select()
                    ->toArray();
                $resultData = [];
                $result_code = 200;
                $result_msg = '加载成功';
                $resultData['list'] = $list;
                $resultData['page'] = $page + 1;
                break;

            default:
                $result_count = $subOrderModel->alias('o')->where($condition)->count();
                if ($result_count <= ($page - 1) * $limit) {
                    $result_code = 203;
                    $result_msg = '没有更多数据了！';
                    $resultData = [];
                    $resultData['list'] = [];
                    $resultData['page'] = $page;
                    $this->result($code, $msg, $result_code, $result_msg, $resultData, $result_count);
                    exit();
                }
                $list = $subOrderModel
                    ->alias('o')
                    ->with(['orderGoods'])
                    ->where($condition)
                    ->field('o.`sub_order_id`,o.`refund_status`,o.`sub_order_sn`,o.`sub_order_sn` as `order_sn`,o.`create_time` as show_time,o.`status`,o.`status` as status_txt,o.`all_price`,o.`total_price`,o.`need_pay`,o.`pay_status`,o.`shipping_type`,o.`pay_type`,o.`total_freight`')
                    ->withAttr('status_txt', function ($value, $data) {
                        return getStatusTxt($value, $data['refund_status'], $data['shipping_type']);
                    })
                    ->withAttr('pay_status', function ($value, $data) {
                        return 1 == $value ? '支付成功' : '未支付';
                    })
                    ->page($page, $limit)
                    ->order('show_time desc')
                    ->group('o.sub_order_sn')
                    ->select()
                    ->toArray();
                $resultData = [];
                $result_code = 200;
                $result_msg = '加载成功';
                $resultData['list'] = $list;
                $resultData['page'] = $page + 1;
                break;
        }


        $this->result($code, $msg, $result_code, $result_msg, $resultData, $result_count);
    }
    /**
     * @xk 获取订单详情
     *
     * @method getOrderInfox
     *
     * @param OrderModel $orderModel [description]
     * @param UserModel  $userModel  [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-05-11T17:05:45+080
     */
    public function getOrderInfox(OrderModel $orderModel, UserModel $userModel)
    {
        $param = request()->param();
        $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
        $order_sn = isset($param['order_sn']) ? $param['order_sn'] : '';
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        if ('' == $user_sn) {
            $result_code = 404;
            $result_msg = '您还没有登录，请先进行登录';
            $this->result($code, $msg, $result_code, $result_msg);
        }
        $user_info = $userModel->where([['user_sn', '=', $user_sn]])->field('`status`,`is_bind`,`tel`')->find();
        if (!$user_info) {
            $result_code = 404;
            $result_msg = '您还没有登录，请先进行登录';
            $this->result($code, $msg, $result_code, $result_msg);
        }
        if (1 != $user_info['status']) {
            $result_code = 404;
            $result_msg = '账户已注销';
            $this->result($code, $msg, $result_code, $result_msg);
        }
        if ($order_sn == '') {
            $result_code = 404;
            $result_msg = '请核对订单编号';
            $this->result($code, $msg, $result_code, $result_msg, $resultData);
        }
        $order_info = $orderModel
            ->where([['order_sn', '=', $order_sn]])
            ->field('`order_id`,`pay_status`,`order_sn`,`need_pay`,`pay_price`,`pay_type`,`pay_code`,`create_time`,`pay_time`')
            ->find();
        if (!$order_info) {
            $result_code = 404;
            $result_msg = '订单不存在';
            $this->result($code, $msg, $result_code, $result_msg, $resultData);
        }

        $result_code = 200;
        $result_msg = '加载成功';
        $resultData['info'] = $order_info;
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 获取订单详情
     *
     * @method getOrderInfo
     *
     * @param OrderModel $orderModel [description]
     * @param UserModel  $userModel  [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-05-11T17:05:45+080
     */
    public function getOrderInfo(OrderModel $orderModel, UserModel $userModel, OrderServices $orderServices)
    {
        $param = request()->param();
        $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
        $order_sn = isset($param['order_sn']) ? $param['order_sn'] : '';
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        if ('' == $user_sn) {
            $result_code = 404;
            $result_msg = '您还没有登录，请先进行登录';
            $this->result($code, $msg, $result_code, $result_msg);
        }
        $user_info = $userModel->where([['user_sn', '=', $user_sn]])->field('`status`,`is_bind`,`tel`')->find();
        if (!$user_info) {
            $result_code = 404;
            $result_msg = '您还没有登录，请先进行登录';
            $this->result($code, $msg, $result_code, $result_msg);
        }
        if (1 != $user_info['status']) {
            $result_code = 404;
            $result_msg = '账户已注销';
            $this->result($code, $msg, $result_code, $result_msg);
        }
        if ($order_sn == '') {
            $result_code = 404;
            $result_msg = '请核对订单编号';
            $this->result($code, $msg, $result_code, $result_msg, $resultData);
        }
        // Db::startTrans();
        try {
            // $orderServices->syncOrderPrice($order_sn);
            $order_info = $orderModel
                ->where([['order_sn', '=', $order_sn]])
                ->field('`order_id`,`pay_status`,`order_sn`,`need_pay`,`pay_price`,`pay_type`,`pay_code`,`create_time`,`pay_time`')
                ->find();
            if (!$order_info) {
                $result_code = 404;
                $result_msg = '订单不存在';
                $this->result($code, $msg, $result_code, $result_msg, $resultData);
            }

            $result_code = 200;
            $result_msg = '加载成功';
            $resultData['info'] = $order_info;
            // Db::commit();
        } catch (\Exception $e) {
            $result_code = $e->getCode();
            $result_msg = $e->getMessage();
            $resultData = [];
            // Db::rollback();
        }

        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 子订单详情获取
     *
     * @method getSubOrderInfo
     * @param  SubOrderModel   $subOrderModel             [description]
     * @param  UserModel       $userModel                 [description]
     * @return [type]          [description]
     * @Time   2021-09-01
     * @City   青岛
     * @Author xkyinzhe        <zhonghuaxinxing@sina.cn>
     */
    public function getSubOrderInfo(SubOrderModel $subOrderModel, UserModel $userModel)
    {
        $param = request()->param();
        $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
        $sub_order_sn = isset($param['order_sn']) ? $param['order_sn'] : '';
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        // if ('' == $user_sn) {
        //     $result_code = 404;
        //     $result_msg = '您还没有登录，请先进行登录';
        //     $this->result($code, $msg, $result_code, $result_msg);
        // }
        // $user_info = $userModel->where([['user_sn', '=', $user_sn]])->field('`status`,`is_bind`,`tel`')->find();
        // if (!$user_info) {
        //     $result_code = 404;
        //     $result_msg = '您还没有登录，请先进行登录';
        //     $this->result($code, $msg, $result_code, $result_msg);
        // }
        // if (1 != $user_info['status']) {
        //     $result_code = 404;
        //     $result_msg = '账户已注销';
        //     $this->result($code, $msg, $result_code, $result_msg);
        // }
        // if (0 == $user_info['is_bind'] && '' == $user_info['tel']) {
        //     $result_code = 404;
        //     $result_msg = '请先绑定手机号！';
        //     $this->result($code, $msg, $result_code, $result_msg);
        // }
        if ($sub_order_sn == '') {
            $result_code = 404;
            $result_msg = '请核对订单编号';
            $this->result($code, $msg, $result_code, $result_msg, $resultData);
        }
        $order_info = $subOrderModel
            ->alias('so')
            ->leftJoin('store s', 's.store_id=so.store_id')
            ->where([['so.sub_order_sn', '=', $sub_order_sn]])
            ->with(['orderGoods'])
            ->field('so.`company_num`,so.`company_code`,so.`sub_order_id`,so.`refund_status`,so.`pay_status`,so.`status`,so.`sub_order_sn`,so.`need_pay`,so.`need_pay` as `pay_price`,so.`pay_type`,so.`pay_code`,so.`create_time`,so.`pay_time`,so.`shipping_type`,so.`self_code_no`,so.`name`,so.`tel`,so.`province`,so.`city`,so.`area`,so.`address`,so.`content`,so.`pay_time`,so.`create_time`,so.`total_price`,so.`all_price`,so.`total_freight`,so.`need_pay`,s.`store_name`,so.`cancel_time`,so.`delivery_time`,so.`pay_status` as pay_status_txt,so.`pay_type` as `pay_type_txt`,so.`status` as status_txt')
            ->withAttr('pay_status_txt', function ($value, $data) {
                return 1 == $value ? '支付成功' : '未支付';
            })->withAttr('status_txt', function ($value, $data) {
                return getStatusTxt($value, $data['refund_status'], $data['shipping_type']);
            })
            ->withAttr('pay_type_txt', function ($value, $data) {
                return 1 == $value ? '微信支付' : ($value == 2 ? '支付宝支付' : '余额支付');
            })
            ->find();
        $resultData['self_info'] = ['self_name' => config('web_config.self_name'), 'self_tel' => config('web_config.self_tel'), 'self_address' => config('web_config.self_address')];
        if (!$order_info) {
            $result_code = 404;
            $result_msg = '订单不存在';
            $this->result($code, $msg, $result_code, $result_msg, $resultData);
        }
        if ($order_info['status'] == 2 && $order_info['shipping_type'] == 2) {
            $resultData['self_qrcode'] = getShowUrl('/' . $subOrderModel->createSelfCode($sub_order_sn));
        }
        // 根据创建时间和
        if ($order_info['status'] == 0) {
            $cancel_config = config('web_config.cancel_hour') * 3600; // 72
            $pass_time = time() - strtotime($order_info['create_time']); // 已经使用时间
            $order_info['drow_cancel_time'] = $cancel_config - $pass_time;
        }
        if ($order_info['status'] == 2) {
            $shipping_config = config('web_config.shipping_hour') * 24 * 3600; // 72
            $pass_time = time() - strtotime($order_info['delivery_time']); // 发货时间已使用
            $order_info['drow_cancel_time'] = $shipping_config - $pass_time;
        }
        $result_code = 200;
        $result_msg = '加载成功';
        $resultData['info'] = $order_info;
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 获取核销端订单详情
     *
     * @method getSubOrderInfo
     * @param  SubOrderModel   $subOrderModel             [description]
     * @param  UserModel       $userModel                 [description]
     * @return [type]          [description]
     * @Time   2021-10-28
     * @City   青岛
     * @Author xkyinzhe        <zhonghuaxinxing@sina.cn>
     */
    public function getCheckSubOrderInfo(SubOrderModel $subOrderModel, UserModel $userModel)
    {
        $param = request()->param();
        $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
        $sub_order_sn = isset($param['order_sn']) ? base64_decode($param['order_sn']) : '';
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        try {
            if ('' == $user_sn) {
                throw new \think\Exception("您还没有登录，请先进行登录", 404);
            }
            $user_info = $userModel->where([['user_sn', '=', $user_sn]])->field('`is_admin`,`status`,`is_bind`,`tel`')->find();
            if (!$user_info) {
                throw new \think\Exception("您还没有登录，请先进行登录", 404);
            }
            if (1 != $user_info['status']) {
                throw new \think\Exception("账户已被冻结，请稍后重试", 404);
            }
            if (0 == $user_info['is_admin']) {
                throw new \think\Exception("您还不是核销员，请联系后台管理员处理", 404);
            }
            $order_info = $subOrderModel
                ->alias('so')
                ->leftJoin('store s', 's.store_id=so.store_id')
                ->where([['so.sub_order_sn', '=', $sub_order_sn]])
                ->with(['orderGoods'])
                ->field('so.`company_num`,so.`company_code`,so.`sub_order_id`,so.`refund_status`,so.`pay_status`,so.`status`,so.`sub_order_sn`,so.`need_pay`,so.`pay_price`,so.`pay_type`,so.`pay_code`,so.`create_time`,so.`pay_time`,so.`shipping_type`,so.`self_code_no`,so.`name`,so.`tel`,so.`province`,so.`city`,so.`area`,so.`address`,so.`content`,so.`pay_time`,so.`create_time`,so.`total_price`,so.`all_price`,so.`total_freight`,so.`need_pay`,s.`store_name`,so.`cancel_time`,so.`delivery_time`')
                ->withAttr('pay_status', function ($value, $data) {
                    return 1 == $value ? '支付成功' : '未支付';
                })
                ->withAttr('pay_type', function ($value, $data) {
                    return 1 == $value ? '微信支付' : ($value == 2 ? '支付宝支付' : '余额支付');
                })
                ->find();
            $resultData['self_info'] = ['self_name' => config('web_config.self_name'), 'self_tel' => config('web_config.self_tel'), 'self_address' => config('web_config.self_address')];
            if (!$order_info) {
                throw new \think\Exception("订单不存在", 404);
                $result_code = 404;
                $result_msg = '订单不存在';
                $this->result($code, $msg, $result_code, $result_msg, $resultData);
            }
            $result_code = 200;
            $result_msg = '加载成功';
            $resultData['info'] = $order_info;
        } catch (\Exception $e) {
            $result_code = 404;
            $result_msg = $e->getMessage();
        }


        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }

    /**
     * @xk 确认收货
     *
     * @method makeSure
     *
     * @param OrderModel $orderModel [description]
     * @param UserModel  $userModel  [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-05-12T09:23:55+080
     */
    public function makeSure(SubOrderModel $subOrderModel, UserModel $userModel, GoodsOrderModel $goodsOrderModel, OrderServices $orderServices, SendMsg $sendMsg)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        try {
            $param = request()->param();
            $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
            $order_sn = isset($param['sub_order_sn']) ? $param['sub_order_sn'] : '';
            if ('' == $user_sn) {
                throw new \think\Exception('您还没有登录，请先登录', 404);
            }
            $user_info = $userModel
                ->where([['user_sn', '=', $user_sn]])
                ->field('`status`,`is_bind`,`tel`')
                ->find();
            if (!$user_info) {
                throw new \think\Exception('您还没有登录，请先登录', 404);
            }
            if (1 != $user_info['status']) {
                throw new \think\Exception('账户已注销', 404);
            }
            if ('' == $order_sn) {
                throw new \think\Exception('请选择需要查看的订单', 404);
            }
            $condition = [];
            $condition[] = ['sub_order_sn', '=', $order_sn];
            // $order_info = $subOrderModel->where($condition)->field('`status`,`user_sn`')->find();
            // 2022-02-10 新增判断条件 如果存在还未完成的首购订单 则不允许其他订单确认收货
            $order_info = $subOrderModel->where($condition)->field('`status`,`user_sn`,`is_buy`,`total_price`,`company_num`,`company_name`')->find();
            if (!$order_info) {
                throw new \think\Exception('订单不存在', 404);
            }
            $first_count = $goodsOrderModel->where([['user_sn', '=', $user_sn], ['status', 'in', '1.1,2.1'], ['is_buy', '=', 0]])->count();
            if ($first_count > 0 && $order_info['is_buy'] != 0) {
                throw new \think\Exception("您存在没有确认收货的首购订单，请先完成首购订单！", 404);
            }
            if (2 != $order_info['status']) {
                throw new \think\Exception('订单当前状态，不允许执行收货', 404);
            }
            // 查看是否存在未处理的售后
            $refund_count = $goodsOrderModel->where($condition)->where([['status', 'in', '5.1,5.11,5.2,5.21,5.23,5.24,5.3,5.31,5.33']])->count();
            if ($refund_count > 0) {
                throw new \think\Exception("当前订单存在未处理的售后，请耐心等待售后处理完成后再进行收货", 404);
            }
            // 执行订单核销
            $res = $subOrderModel
                ->where($condition)
                ->save(['status' => 3, 'receiving_time' => date('Y-m-d H:i:s')]);
            // 修改所有状态正常的商品
            $condition[] = ['status', 'in', '2.1,5.12,5.22,5.32,5.34']; // 所有待收货或待核销商品订单 状态修改为已核销
            $order_goods_res = $goodsOrderModel
                ->where($condition)
                ->save(['status' => '3.1', 'order_status' => 3, 'receiving_time' => date('Y-m-d H:i:s')]);
            $orderServices->syncFinance($order_sn); //  订单收货 或 核销 开始执行业绩结算
            $create_data = [];
            $create_data['sub_order_sn'] = $order_sn;
            $create_data['total_price'] = $order_info['total_price'];
            $create_data['company_name'] = $order_info['company_name'];
            $create_data['company_num'] = $order_info['company_num'];
            $content = '尊敬的用户，您的订单编号为' . $order_sn . '的订单已经确认收货成功！';
            $sendMsg->sendPushMsg($order_info['user_sn'], '签收通知', $content, 4, $create_data);
            Db::commit();
            $result_code = 200;
            $result_msg = '确认收货成功';
        } catch (\Exception $e) {
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 核销员核销
     *
     * @method doSelf
     * @param  SubOrderModel   $subOrderModel             [description]
     * @param  UserModel       $userModel                 [description]
     * @param  OrderGoodsModel $orderGoodsModel           [description]
     * @param  OrderServices   $orderServices             [description]
     * @return [type]          [description]
     * @Time   2021-10-28
     * @City   青岛
     * @Author xkyinzhe        <zhonghuaxinxing@sina.cn>
     */
    public function doSelf(SubOrderModel $subOrderModel, UserModel $userModel, GoodsOrderModel $goodsOrderModel, OrderServices $orderServices)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        try {
            $param = request()->param();
            $check_user_sn = isset($param['check_user_sn']) ? $param['check_user_sn'] : '';
            $order_sn = isset($param['sub_order_sn']) ? $param['sub_order_sn'] : '';
            if ('' == $check_user_sn) {
                throw new \think\Exception('您还没有登录，请先登录', 404);
            }
            $user_info = $userModel
                ->where([['user_sn', '=', $check_user_sn]])
                ->field('`status`,`is_admin`,`is_bind`,`tel`')
                ->find();
            if (!$user_info) {
                throw new \think\Exception('您还没有登录，请先登录', 404);
            }
            if (1 != $user_info['status']) {
                throw new \think\Exception('账户已注销', 404);
            }
            if (1 != $user_info['is_admin']) {
                throw new \think\Exception('您没有核销权限，请联系管理员进行处理', 404);
            }
            if ('' == $order_sn) {
                throw new \think\Exception('请重新处理需要核销的订单', 404);
            }
            $condition = [];
            $condition[] = ['sub_order_sn', '=', $order_sn];
            $order_info = $subOrderModel->where($condition)->field('`status`,`user_sn`')->find();
            if (!$order_info) {
                throw new \think\Exception('订单不存在', 404);
            }
            if (2 != $order_info['status']) {
                throw new \think\Exception('订单当前不处于可以进行核销的状态', 404);
            }
            // 查看是否存在未处理的售后
            $refund_count = $goodsOrderModel->where($condition)->where([['status', 'in', '5.1,5.11,5.2,5.21,5.23,5.24,5.3,5.31']])->count();
            if ($refund_count > 0) {
                throw new \think\Exception("当前订单存在未处理的售后，请先处理完成售后之后在进行核销", 404);
            }
            // 执行订单核销
            $res = $subOrderModel
                ->where($condition)
                ->save(['status' => 3, 'receiving_time' => date('Y-m-d H:i:s')]);
            // 修改所有状态正常的商品
            $condition[] = ['status', 'in', '2.1,5.12,5.22,5.32']; // 所有待收货或待核销商品订单 状态修改为已核销
            $order_goods_res = $goodsOrderModel
                ->where($condition)
                ->save(['status' => '3.1', 'order_status' => 3, 'receiving_time' => date('Y-m-d H:i:s')]);
            $orderServices->syncFinance($order_sn); //  订单收货 或 核销 开始执行业绩结算
            Db::commit();
            $result_code = 200;
            $result_msg = '确认收货成功';
        } catch (\Exception $e) {
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }

    /**
     * @xk 取消订单
     *
     * @method cancelOrder
     *
     * @param OrderModel $orderModel [description]
     * @param UserModel  $userModel  [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-05-12T09:24:16+080
     */
    public function cancelOrder(OrderModel $orderModel, SubOrderModel $subOrderModel, UserModel $userModel, GoodsOrderModel $goodsOrderModel, OrderServices $orderServices)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        try {
            $param = request()->param();
            $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
            $order_sn = isset($param['sub_order_sn']) ? $param['sub_order_sn'] : '';
            if ('' == $user_sn) {
                throw new \think\Exception('您还没有登录，请先登录', 404);
            }
            $user_info = $userModel->where([['user_sn', '=', $user_sn]])->field('`status`,`is_bind`,`tel`')->find();
            if (!$user_info) {
                throw new \think\Exception('您还没有登录，请先登录', 404);
            }
            if (1 != $user_info['status']) {
                throw new \think\Exception('账户已注销', 404);
            }
            if ('' == $order_sn) {
                throw new \think\Exception('请选择需要查看的订单', 404);
            }
            $condition = [];
            $condition[] = ['order_sn', '=', $order_sn];
            $order_info = $orderModel->where($condition)->field('`status`')->find();
            if (!$order_info) {
                throw new \think\Exception('订单不存在', 404);
            }
            if ($order_info['status'] != 0) {
                throw new \think\Exception("订单当前进入其他状态，不需要自动取消", 404);
            }
            $order_data = [];
            // 未付款 状态直接取消
            $order_data['status'] = 6; // 订单取消
            $order_data['cancel_time'] = date('Y-m-d H:i:s'); // 取消订单时间
            $result_code = 200;
            $result_msg = '订单取消成功';
            $res = $orderModel->where($condition)->save($order_data);
            $res = $subOrderModel->where($condition)->save($order_data);
            $order_goods_res = $goodsOrderModel
                ->where($condition)
                ->save(['status' => '6.1', 'order_status' => 6]);
            // 需要恢复 产品对应的库存
            // echo "11212312"; die();
            // Db::rollback();
            // $orderServices->syncStock($order_sn, 'inc'); // 取消订单 需要退还原来的库存
            // 需要恢复 产品对应的库存
            $sub_order_arr = $subOrderModel->where($condition)->column('sub_order_sn');
            if ($sub_order_arr) {
                foreach ($sub_order_arr as $key => $value) {
                    $orderServices->syncStock($value, 'inc'); // 取消订单
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 立即支付
     *
     * @method goPay
     * @param  OrderModel $orderModel                [description]
     * @param  UserModel  $userModel                 [description]
     * @param  Unionpay   $unionpay                  [description]
     * @return [type]     [description]
     * @Time   2021-10-22
     * @City   青岛
     * @Author xkyinzhe   <zhonghuaxinxing@sina.cn>
     */
    public function goPay(OrderModel $orderModel, UserModel $userModel, Unionpay $unionpay, UserServices $userServices, SubOrderModel $subOrderModel)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        try {
            $param = request()->param();
            $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
            $order_sn = isset($param['order_sn']) ? $param['order_sn'] : '';
            $sub_order_sn = isset($param['sub_order_sn']) ? $param['sub_order_sn'] : '';
            $pay_type = isset($param['pay_type']) ? $param['pay_type'] : '1';
            $be_from = isset($param['be_from']) ? $param['be_from'] : 'H5';
            $type = isset($param['type']) ? $param['type'] : 'all';
            if ('' == $user_sn) {
                throw new \think\Exception('您还没有登录，请先登录', 404);
            }

            // 重新规划和计算订单支付金额 如果订单金额改变 需要调整对应的订单编号
            //

            switch ($pay_type) {
                case '1':
                    switch ($type) {
                        case 'all':
                            $condition = [];
                            $condition[] = ['o.order_sn', '=', $order_sn];
                            $order_info = $orderModel
                                ->alias('o')
                                ->leftJoin('user u', 'u.user_sn = o.user_sn')
                                ->where($condition)
                                ->field('o.`pay_status`,o.`order_sn`,o.`status`,o.`user_sn`,o.`need_pay`,u.`wechat_app_openId`,u.`wechat_openId`')
                                ->find();
                            if (!$order_info) {
                                throw new \think\Exception('订单不存在', 404);
                            }
                            if (0 != $order_info['pay_status'] || $order_info['status'] != 0) {
                                throw new \think\Exception('当前订单不属于未支付状态', 404);
                            }
                            $url = $unionpay->wecahtPay($order_info, $be_from);
                            break;
                        case 'sub':
                            $condition = [];
                            $order_info = [];
                            $condition[] = ['sub.sub_order_sn', '=', $sub_order_sn];
                            $order_info = $subOrderModel
                                ->alias('sub')
                                ->leftJoin('user u', 'u.user_sn = sub.user_sn')
                                ->where($condition)
                                ->field('sub.`pay_status`,sub.`status`,sub.`sub_order_sn`,sub.`user_sn`,sub.`need_pay`,u.`wechat_app_openId`,u.`wechat_openId`')
                                ->find();
                            if (!$order_info) {
                                throw new \think\Exception('订单不存在', 404);
                            }
                            if (0 != $order_info['pay_status'] || $order_info['status'] != 0) {
                                throw new \think\Exception('当前订单不属于未支付状态', 404);
                            }
                            if ($order_info['wechat_app_openId'] == '' && $be_from == 'wxapp') {
                                $resultData['jumpUrl'] = "/pages/login/bindWechat";
                                throw new \think\Exception("您还没有完成小程序授权，请先授权小程序登录", 300);
                            }
                            $url = $unionpay->subOrderPay($order_info, $be_from);
                            break;
                    }
                    $result_code = 200;
                    $result_msg = '请进行支付';
                    if ($be_from == 'H5') {
                        $resultData['jumpUrl'] = $url;
                        $resultData['pay_type'] = $pay_type;
                    } else {
                        $resultData['pay_info'] = $url;
                        $resultData['order_sn'] = $order_sn;
                        $resultData['pay_type'] = $pay_type;
                        $resultData['sub_order_sn'] = $sub_order_sn;
                    }
                    break;
                case '2':
                    switch ($type) {
                        case 'all':
                            $condition = [];
                            $condition[] = ['o.order_sn', '=', $order_sn];
                            $order_info = $orderModel
                                ->alias('o')
                                ->leftJoin('user u', 'u.user_sn = o.user_sn')
                                ->where($condition)
                                ->field('o.`pay_status`,o.`order_sn`,o.`status`,o.`user_sn`,o.`need_pay`,u.`wechat_app_openId`,u.`wechat_openId`')
                                ->find();
                            if (!$order_info) {
                                throw new \think\Exception('订单不存在', 404);
                            }
                            if (0 != $order_info['pay_status'] || $order_info['status'] != 0) {
                                throw new \think\Exception('当前订单不属于未支付状态', 404);
                            }
                            $url = $unionpay->aliPay($order_info, $be_from);
                            break;
                        case 'sub':
                            $condition = [];
                            $order_info = [];
                            $condition[] = ['sub.sub_order_sn', '=', $sub_order_sn];
                            $order_info = $subOrderModel
                                ->alias('sub')
                                ->leftJoin('user u', 'u.user_sn = sub.user_sn')
                                ->where($condition)
                                ->field('sub.`pay_status`,sub.`status`,sub.`sub_order_sn`,sub.`user_sn`,sub.`need_pay`,u.`wechat_app_openId`,u.`wechat_openId`')
                                ->find();
                            if (!$order_info) {
                                throw new \think\Exception('订单不存在', 404);
                            }
                            if (0 != $order_info['pay_status'] || $order_info['status'] != 0) {
                                throw new \think\Exception('当前订单不属于未支付状态', 404);
                            }
                            $url = $unionpay->subOrderAliPay($order_info, $be_from);
                            break;
                    }
                    $result_code = 200;
                    $result_msg = '请进行支付';
                    $resultData['pay_info'] = $url;
                    $resultData['order_sn'] = $order_sn;
                    $resultData['pay_type'] = $pay_type;
                    $resultData['sub_order_sn'] = $sub_order_sn;
                    break;
                case '3':
                    switch ($type) {
                        case 'all':
                            $condition = [];
                            $condition[] = ['o.order_sn', '=', $order_sn];
                            $order_info = $orderModel
                                ->alias('o')
                                ->leftJoin('user u', 'u.user_sn = o.user_sn')
                                ->where($condition)
                                ->field('o.`pay_status`,o.`order_sn`,o.`status`,o.`user_sn`,o.`need_pay`,u.`wechat_app_openId`,u.`wechat_openId`')
                                ->find();
                            if (!$order_info) {
                                throw new \think\Exception('订单不存在', 404);
                            }
                            if (0 != $order_info['pay_status'] || $order_info['status'] != 0) {
                                throw new \think\Exception('当前订单不属于未支付状态', 404);
                            }
                            $result = $userServices->shopPay($order_info);
                            $result_code = 200;
                            $result_msg = '支付成功';
                            break;
                        case 'sub':
                            $condition = [];
                            $order_info = [];
                            $condition[] = ['sub.sub_order_sn', '=', $sub_order_sn];
                            $order_info = $subOrderModel
                                ->alias('sub')
                                ->where($condition)
                                ->field('sub.`pay_status`,sub.`status`,sub.`sub_order_sn`,sub.`user_sn`,sub.`need_pay`')
                                ->find();
                            if (!$order_info) {
                                throw new \think\Exception('订单不存在', 404);
                            }
                            if (0 != $order_info['pay_status'] || $order_info['status'] != 0) {
                                throw new \think\Exception('当前订单不属于未支付状态', 404);
                            }
                            $result = $userServices->shopSubPay($order_info);
                            $result_code = 200;
                            $result_msg = '支付成功';
                            break;
                    }
                    break;
                case '4':
                    switch ($type) {
                        case 'all':
                            $condition = [];
                            $condition[] = ['o.order_sn', '=', $order_sn];
                            $order_info = $orderModel
                                ->alias('o')
                                ->leftJoin('user u', 'u.user_sn = o.user_sn')
                                ->where($condition)
                                ->field('o.`pay_status`,o.`order_sn`,o.`status`,o.`user_sn`,o.`need_pay`,u.`wechat_app_openId`,u.`wechat_openId`')
                                ->find();
                            if (!$order_info) {
                                throw new \think\Exception('订单不存在', 404);
                            }
                            if (0 != $order_info['pay_status'] || $order_info['status'] != 0) {
                                throw new \think\Exception('当前订单不属于未支付状态', 404);
                            }
                            $url = $unionpay->uniPay($order_info, $be_from);
                            break;
                        case 'sub':
                            $condition = [];
                            $order_info = [];
                            $condition[] = ['sub.sub_order_sn', '=', $sub_order_sn];
                            $order_info = $subOrderModel
                                ->alias('sub')
                                ->leftJoin('user u', 'u.user_sn = sub.user_sn')
                                ->where($condition)
                                ->field('sub.`pay_status`,sub.`status`,sub.`sub_order_sn`,sub.`user_sn`,sub.`need_pay`,u.`wechat_app_openId`,u.`wechat_openId`')
                                ->find();
                            if (!$order_info) {
                                throw new \think\Exception('订单不存在', 404);
                            }
                            if (0 != $order_info['pay_status'] || $order_info['status'] != 0) {
                                throw new \think\Exception('当前订单不属于未支付状态', 404);
                            }
                            if ($order_info['wechat_app_openId'] == '' && $be_from == 'wxapp') {
                                $resultData['jumpUrl'] = "/pages/login/bindWechat";
                                throw new \think\Exception("您还没有完成小程序授权，请先授权小程序登录", 300);
                            }
                            $url = $unionpay->subUniPay($order_info, $be_from);
                            break;
                    }
                    $result_code = 200;
                    $result_msg = '请进行支付';
                    if ($be_from == 'H5') {
                        $resultData['jumpUrl'] = $url;
                        $resultData['pay_type'] = $pay_type;
                    } else {
                        $resultData['pay_info'] = $url;
                        $resultData['order_sn'] = $order_sn;
                        $resultData['pay_type'] = $pay_type;
                        $resultData['sub_order_sn'] = $sub_order_sn;
                    }
                    break;
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            if ($e->getCode() == 300) {
                $result_code = 300;
            }
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 查询快递100信息
     *
     * @method searchShipping
     *
     * @param OrderModel $orderModel [description]
     * @param UserModel  $userModel  [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-05-12T09:58:52+080
     */
    public function searchShipping()
    {
        $param = request()->param();
        $company_num = isset($param['company_num']) ? $param['company_num'] : '';
        $company_code = isset($param['company_code']) ? $param['company_code'] : '';
        $tel = isset($param['tel']) ? $param['tel'] : '';
        $appcode = config('core_config.aliyun_express.appcode');
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        if ('' == $company_num) {
            $result_code = 404;
            $result_msg = '请确认物流单号';
            $this->result($code, $msg, $result_code, $result_msg);
        }
        $company_num = $company_num . ':' . substr($tel, -4);
        $url = 'https://wuliu.market.alicloudapi.com/kdi?no=' . $company_num;
        $headers = [
            'Authorization:APPCODE ' . $appcode
        ];
        $result = https_request($url, [], $headers);
        $data = json_decode($result, true);
        $result_code = 200;
        $result_msg = '加载成功';
        $resultData = [];
        if ($data['msg'] == 'ok' && $data['status'] == 0) {
            foreach ($data['result']['list'] as $key => $value) {
                $show_data = [];
                $show_data['show_date'] =  chanageDateString($value['time'], 7);
                $show_data['show_time'] = chanageDateString($value['time'], 8);
                $show_data['content'] = $value['status'];
                $show_data['time'] = $value['time'];
                $resultData[] = $show_data;
            }
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 获取订单产品详情
     *
     * @method getGoodsOrderInfo
     * @param  SubOrderModel     $subOrderModel             [description]
     * @param  OrderGoodsModel   $orderGoodsModel           [description]
     * @return [type]            [description]
     * @Time   2021-09-03
     * @City   青岛
     * @Author xkyinzhe          <zhonghuaxinxing@sina.cn>
     */
    public function getGoodsOrderInfo(SubOrderModel $subOrderModel, GoodsOrderModel $goodsOrderModel)
    {
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        try {
            $param = request()->param();
            $sub_order_sn = isset($param['sub_order_sn']) ? $param['sub_order_sn'] : '';
            $goods_order_sn = isset($param['goods_order_sn']) ? $param['goods_order_sn'] : 0;
            $condition = [];
            $condition[] = ['sub_order_sn', '=', $sub_order_sn];
            $order_info = $subOrderModel->where($condition)->field('`pay_status`,`status`,`total_freight`')->find();
            if (!$order_info) {
                throw new \think\Exception("订单不存在，请稍后重试", 404);
            }
            if ($order_info['pay_status'] != 1 || $order_info['status'] < 1) {
                throw new \think\Exception("订单还未支付，无需执行售后操作", 404);
            }
            $condition[] = ['goods_order_sn', '=', $goods_order_sn];
            $goods_info = $goodsOrderModel
                ->where($condition)
                ->field('*')
                ->withAttr('pay_price', function ($value, $data) {
                    return $value;
                })
                ->find();
            if (!$goods_info) {
                throw new \think\Exception("您要申请售后的产品不存在，无法进行申请", 404);
            }
            if (($goods_info['status'] < 1 || ($goods_info['status'] > 4.1) && $goods_info['status'] != 5.12 && $goods_info['status'] != 5.22 && $goods_info['status'] != 5.32)) {
                throw new \think\Exception("当前产品不可申请售后操作", 404);
            }
            // 开始判断 当前产品的运费计算方式
            if ($goods_info) {
                if ($goods_info['freight_type'] == 1) {
                    // 按照单件进行运费计算的情况
                    $goods_info['refund_want_price'] = $goods_info['total']; // 申请退款总金额
                    $goods_info['refund_freight'] = $goods_info['freight']; // 申请退款运费
                } elseif ($goods_info['freight_type'] == 2 || $goods_info['freight_type'] == 0) {
                    $order_condition = [];
                    $order_condition[] = ['sub_order_sn', '=', $sub_order_sn];
                    // 如果是整单进行金额计算
                    // 判断当前商品是否是最后一个申请售后的商品 如果是则获取运费
                    $order_all = $goodsOrderModel->where($order_condition)->count(); //全部订单产品
                    $has_order = $goodsOrderModel
                        ->where($order_condition)
                        ->where([['status', 'in', '5.1,5.11,5.13,5.14,5.2,5.21,5.23,5.24,5.25,5.26,5.3,5.31,5.33']])
                        ->count();
                    // 如果总数量 小于等于当前售后数量+1
                    if ($order_all <= ($has_order + 1) && $order_info['status'] == 1) {
                        $goods_info['refund_want_price'] = sprintf('%.2f', ((float)$goods_info['sub_total'] + (float)$order_info['total_freight']));
                        $goods_info['refund_freight'] = $order_info['total_freight'];
                    } else {
                        $goods_info['refund_want_price'] = $goods_info['sub_total'];
                        $goods_info['refund_freight'] = 0;
                    }
                }
            }
            $resultData['order_info'] = $order_info;
            $resultData['goods_info'] = $goods_info;
            $resultData['refund_address_info'] = '收货人：' . config('web_config.refund_address_name') . '<br/>' . '电话：' . config('web_config.refund_address_tel') . '<br/>' . '地址：' . config('web_config.refund_address');
            $result_code = 200;
            $result_msg = '获取成功';
        } catch (\Exception $e) {
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 提交退款申请
     *
     * @method refundPaySave
     * @param  SubOrderModel         $subOrderModel             [description]
     * @param  OrderGoodsModel       $orderGoodsModel           [description]
     * @param  OrderGoodsRefundModel $orderGoodsRefundModel     [description]
     * @return [type]                [description]
     * @Time   2021-09-03
     * @City   青岛
     * @Author xkyinzhe              <zhonghuaxinxing@sina.cn>
     */
    public function refundPaySave(SubOrderModel $subOrderModel, GoodsOrderModel $goodsOrderModel, RefundOrderModel $refundOrderModel, Task $taskService)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        try {
            $param = request()->param();
            $sub_order_sn = isset($param['sub_order_sn']) ? $param['sub_order_sn'] : '';
            $goods_order_sn = isset($param['goods_order_sn']) ? $param['goods_order_sn'] : 0;
            $order_goods_refund_id = isset($param['order_goods_refund_id']) ? $param['order_goods_refund_id'] : 0;
            if ($order_goods_refund_id <= 0) {
                unset($param['order_goods_refund_id']);
            }
            $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
            $reason = isset($param['reason']) ? $param['reason'] : '';
            $content = isset($param['content']) ? $param['content'] : '';
            $return_reason = isset($param['return_reason']) ? $param['return_reason'] : '';
            $refund_want_price = isset($param['refund_want_price']) ? $param['refund_want_price'] : 0.00;
            $reason_picarr = isset($param['reason_picarr']) && $param['reason_picarr'] != '' ? implode(',', $param['reason_picarr']) : '';
            $return_reason_picarr = isset($param['return_reason_picarr']) && $param['return_reason_picarr'] != '' ? implode(',', $param['return_reason_picarr']) : '';
            $type = isset($param['type']) ? $param['type'] : 1;
            $act = isset($param['act']) ? $param['act'] : 'create';
            $is_get_goods = isset($param['is_get_goods']) ? $param['is_get_goods'] : 1;
            $status = isset($param['status']) ? $param['status'] : 0;
            $order_condition = [];
            $order_condition[] = ['sub_order_sn', '=', $sub_order_sn];
            $order_info = $subOrderModel->where($order_condition)->field('`pay_status`,`status`,`total_freight`')->find();
            if (!$order_info) {
                throw new \think\Exception("您要进行退款的订单已经不存在，请稍后重试", 404);
            }
            if ($order_info['pay_status'] != 1 || $order_info['status'] < 1) {
                throw new \think\Exception("订单还未支付，无需执行售后操作", 404);
            }
            $condition = $order_condition;
            $condition[] = ['goods_order_sn', '=', $goods_order_sn];
            $goods_info = $goodsOrderModel
                ->where($condition)
                ->field('*')
                ->withAttr('goods_pic', function ($value, $data) {
                    return getShowUrl($value);
                })
                ->find();

            if (!$goods_info) {
                throw new \think\Exception("您要申请售后的产品不存在，无法进行申请", 404);
            }
            if (($goods_info['status'] < 1 || ($goods_info['status'] > 4.1) && $goods_info['status'] != 5.12 && $goods_info['status'] != 5.22 && $goods_info['status'] != 5.32)) {
                throw new \think\Exception("当前产品不可申请售后操作", 404);
            }
            $refund_data = [];
            $refund_data['sub_order_sn'] = $sub_order_sn;
            $refund_data['user_sn'] = $user_sn;
            $refund_data['goods_order_sn'] = $goods_order_sn;
            $refund_data['reason'] = $reason;
            $refund_data['return_reason'] = $return_reason;
            $refund_data['refund_want_price'] = $refund_want_price;
            $refund_data['reason_picarr'] = $reason_picarr;
            $refund_data['return_reason_picarr'] = $return_reason_picarr;
            $refund_data['type'] = $type;
            $refund_data['content'] = $content;
            $refund_data['is_get_goods'] = $is_get_goods;
            $refund_data['refund_order_sn'] = $refundOrderModel->getCodeNo(date('YmdHis'), 20, 1, 'refund_order_sn');
            $refund_data['store_id'] = $goods_info['store_id'];

            // 退货/退款订单生成  等待审核
            $order_all = $goodsOrderModel->where($order_condition)->count(); //全部订单产品
            $has_order = $goodsOrderModel
                ->where($order_condition)
                ->where([['status', 'in', '5.1,5.11,5.13,5.2,5.21,5.23,5.24,5.25,5.26,5.3,5.31,5.33']])
                ->count();
            $refund_status = 1;
            if ($order_all <= ($has_order + 1)) {
                $refund_status = 2;
                // 如果是全部退款 则开始获取当前订单的运费
                // 此处增加逻辑运算
                // $all_cost = $order_info['total_freight'];
                // if($all_cost > 0 && $order_info['status'] = 1){
                //   // 没发货的情况下 退运费
                //   $refund_data['refund_want_price'] = (float)$refund_want_price+(float)$all_cost;
                // }
            }
            switch ($act) {
                case 'create':
                    $refund_data['order_status'] = $order_info['status'];
                    $refund_data['goods_status'] = $goods_info['status'];
                    $refund_res = $refundOrderModel->create($refund_data);
                    $refund_id = $refund_res->order_goods_refund_id;
                    break;
                case 'edit':
                    $refund_data['status'] = 0;
                    $refund_data['apply_reason'] = '';
                    $refund_res = $refundOrderModel->find($param['order_goods_refund_id'])->save($refund_data);
                    $refund_id = $param['order_goods_refund_id'];
                    break;
            }
            $resultData['order_goods_refund_id'] = $refund_id;

            $order_res = $subOrderModel
                ->where($order_condition)
                ->find()
                ->save(['refund_want_time' => date('Y-m-d H:i:s'), 'refund_status' => $refund_status]);
            // 订单状态 修改为 全部退款还是部分退款
            $status = 5.1;
            if ($type == 2) {
                $status = 5.2;
            } else if ($type == 3) {
                $status = 5.3;
            }
            $goods_res = $goodsOrderModel
                ->where($condition)
                ->find()
                ->save(['status' => $status]);
            // 判断是退款申请 还是退货申请 退款申请开始写入计划任务 定时审核
            // if ($type == 1) {
            // 执行退款计划
            // $msgData = ['time' => date('YmdHis'), 'msgId' => $refund_data['refund_order_sn'], 'jobAction' => 'refundPay'];
            // $delay = 60;
            // $taskService->put($msgData, $delay);
            // }
            $result_code = 200;
            $result_msg = '申请成功';
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 获取售后订单信息
     *
     * @method getRefundOrderInfo
     * @param  OrderGoodsRefundModel $orderGoodsRefundModel     [description]
     * @return [type]                [description]
     * @Time   2021-09-03
     * @City   青岛
     * @Author xkyinzhe              <zhonghuaxinxing@sina.cn>
     */
    public function getRefundOrderInfo(OrderGoodsRefundModel $orderGoodsRefundModel)
    {
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        try {
            $param = request()->param();
            $sub_order_sn = isset($param['sub_order_sn']) ? $param['sub_order_sn'] : '';
            $order_goods_id = isset($param['order_goods_id']) ? $param['order_goods_id'] : 0;
            $order_goods_refund_id = isset($param['order_goods_refund_id']) ? $param['order_goods_refund_id'] : 0;
            $condition = [];
            if ($sub_order_sn != '') {
                $condition[] = ['orf.sub_order_sn', '=', $sub_order_sn];
            }
            if ($order_goods_id > 0) {
                $condition[] = ['orf.order_goods_id', '=', $order_goods_id];
            }
            if ($order_goods_refund_id > 0) {
                $condition[] = ['orf.order_goods_refund_id', '=', $order_goods_refund_id];
            }
            $condition[] = ['orf.status', 'not in', '3']; // 不是已经撤销或取消的申请
            $info = $orderGoodsRefundModel
                ->alias('orf')
                ->leftJoin('orderGoods og', 'orf.order_goods_id=og.order_goods_id')
                ->leftJoin('subOrder so', 'so.sub_order_sn=orf.sub_order_sn')
                ->leftJoin('store s', 's.store_id=orf.store_id')
                ->where($condition)
                ->field('orf.*,orf.status as show_status,og.order_goods_id,og.`freight_type`,og.goods_id,og.goods_price,og.goods_name,og.goods_pic,og.spec_value,og.total,og.avg_coupon_price,og.sub_coupon_price,og.buy_num,so.pay_type as order_pay_type,orf.`return_reason_picarr` as return_reason_picarr_show,s.`store_name`,s.`tel` as `store_tel`')
                ->withAttr('goods_pic', function ($value, $data) {
                    if ($value) {
                        return getShowUrl($value);
                    }
                })
                ->withAttr('return_reason_picarr_show', function ($value, $data) {
                    if ($value) {
                        return getPicArr($value);
                    }
                })
                ->withAttr('return_reason_picarr', function ($value, $data) {
                    if ($value) {
                        return explode(",", $value);
                    }
                })
                ->find();


            $resultData['info'] = $info;
            $result_code = 200;
            $result_msg = '加载成功';
        } catch (\Exception $e) {
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 取消售后申请
     *
     * @var [type]
     */
    public function orderGoodsRefundCancel(GoodsOrderModel $goodsOrderModel, SubOrderModel $subOrderModel, RefundOrderModel $refundOrderModel)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        try {
            $param = request()->param();
            $sub_order_sn = isset($param['sub_order_sn']) ? $param['sub_order_sn'] : '';
            $goods_order_sn = isset($param['goods_order_sn']) ? $param['goods_order_sn'] : 0;
            if ($sub_order_sn == '' || $goods_order_sn == '') {
                throw new \think\Exception("请选择需要取消的售后申请", 404);
            }
            $order_goods_refund_info = $refundOrderModel
                ->where([['sub_order_sn', '=', $sub_order_sn], ['goods_order_sn', '=', $goods_order_sn]])
                ->find();
            if (!$order_goods_refund_info) {
                throw new \think\Exception("售后申请订单不存在，请重试", 404);
            }
            // echo $order_goods_refund_info['status']; die();
            if ($order_goods_refund_info['status'] != 1.2 && $order_goods_refund_info['status'] != 0 && $order_goods_refund_info['status'] != 2.1) {
                throw new \think\Exception("当前订单状态不允许撤销", 404);
            }
            // 开始执行撤销
            $order_goods_refund_res = $refundOrderModel->destroy($order_goods_refund_info['refund_order_id']);
            // ->where([['sub_order_sn','=',$sub_order_sn],['goods_order_sn','=',$goods_order_sn]])
            // ->save(['status'=>3,'finish_time'=>date('Y-m-d H:i:s')]); // 自主关闭
            $order_condition = [];
            $order_condition[] = ['sub_order_sn', '=', $order_goods_refund_info['sub_order_sn']];
            $condition = [];
            $condition[] = $order_condition;
            $condition[] = ['goods_order_sn', '=', $order_goods_refund_info['goods_order_sn']];
            $order_goods_res = $goodsOrderModel
                ->where($condition)
                ->save(['status' => $order_goods_refund_info['goods_status']]);
            // 退货/退款订单生成  等待审核
            $has_order = $goodsOrderModel
                ->where($order_condition)
                ->where([['status', 'in', '5.1,5.11,5.13,5.14,5.2,5.21,5.23,5.24,5.25,5.26,5.3,5.31,5.33']])
                ->count();
            $order_status = 0;
            if ($has_order > 0) {
                $order_status = 1;
            }
            $order_res = $subOrderModel
                ->where($order_condition)
                ->find()
                ->save(['refund_want_time' => null, 'refund_status' => $order_status]);
            Db::commit();
            $result_code = 200;
            $result_msg = '售后申请取消成功';
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 买家发货
     *
     * @method createShipping
     * @param  OrderGoodsModel       $orderGoodsModel           [description]
     * @param  SubOrderModel         $subOrderModel             [description]
     * @param  OrderGoodsRefundModel $orderGoodsRefundModel     [description]
     * @return [type]                [description]
     * @Time   2021-09-26
     * @City   青岛
     * @Author xkyinzhe              <zhonghuaxinxing@sina.cn>
     */
    public function createShipping(GoodsOrderModel $goodsOrderModel, SubOrderModel $subOrderModel, RefundOrderModel $refundOrderModel)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        try {
            $param = request()->param();
            $sub_order_sn = isset($param['sub_order_sn']) ? $param['sub_order_sn'] : '';
            $goods_order_sn = isset($param['goods_order_sn']) ? $param['goods_order_sn'] : 0;
            if ($sub_order_sn == '' || $goods_order_sn == '') {
                throw new \think\Exception("请选择需要取消的售后申请", 404);
            }
            $order_goods_refund_info = $refundOrderModel
                ->where([['sub_order_sn', '=', $sub_order_sn], ['goods_order_sn', '=', $goods_order_sn]])
                ->find();
            if (!$order_goods_refund_info) {
                throw new \think\Exception("售后申请订单不存在，请重试", 404);
            }
            if ($order_goods_refund_info['status'] != 2.1) {
                throw new \think\Exception("当前订单不允许提交退货物流", 404);
            }
            $param['status'] = 2.3;
            // 开始执行撤销
            $order_goods_refund_res = $refundOrderModel
                ->where([['sub_order_sn', '=', $sub_order_sn], ['goods_order_sn', '=', $goods_order_sn]])
                ->find()
                ->save($param);
            $order_condition = [];
            $order_condition[] = ['sub_order_sn', '=', $order_goods_refund_info['sub_order_sn']];
            $condition = [];
            $condition[] = $order_condition;
            $condition[] = ['goods_order_sn', '=', $order_goods_refund_info['goods_order_sn']];
            $order_goods_res = $goodsOrderModel
                ->where($condition)
                ->save(['status' => '5.23']);
            Db::commit();
            $result_code = 200;
            $result_msg = '发货成功，请等待卖家审核';
        } catch (\Exception $e) {
            Db::rollback();
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 订单删除
     * @param  SubOrderModel $subOrderModel               [description]
     * @param  UserModel     $userModel                   [description]
     * @return [type]                       [description]
     */
    public function deleteOrder(SubOrderModel $subOrderModel, UserModel $userModel)
    {
        Db::startTrans();
        $code = 200;
        $msg = '请求成功';
        $resultData = [];
        try {
            $param = request()->param();
            $user_sn = isset($param['user_sn']) ? $param['user_sn'] : '';
            $sub_order_sn = isset($param['sub_order_sn']) ? $param['sub_order_sn'] : '';
            if ('' == $user_sn) {
                throw new \think\Exception('您还没有登录，请先登录', 404);
            }
            $user_info = $userModel->where([['user_sn', '=', $user_sn]])->field('`status`,`is_bind`,`tel`')->find();
            if (!$user_info) {
                throw new \think\Exception('您还没有登录，请先登录', 404);
            }
            if (1 != $user_info['status']) {
                throw new \think\Exception('账户已注销', 404);
            }
            if ('' == $sub_order_sn) {
                throw new \think\Exception('请选择需要查看的订单', 404);
            }
            $condition = [];
            $condition[] = ['sub_order_sn', '=', $sub_order_sn];
            $order_info = $subOrderModel->where($condition)->field('`status`,`sub_order_id`')->find();
            if (!$order_info) {
                throw new \think\Exception('订单不存在', 404);
            }
            if (6 != $order_info['status'] && $order_info['status'] != 3) {
                throw new \think\Exception('订单当前状态不允许删除', 404);
            }
            $res = $subOrderModel->destroy($order_info['sub_order_id']);
            Db::commit();
            $result_code = 200;
            $result_msg = '订单删除成功';
        } catch (\Exception $e) {
            $result_code = 404;
            $result_msg = $e->getMessage();
        }
        $this->result($code, $msg, $result_code, $result_msg, $resultData);
    }
    /**
     * @xk 申请售后原因
     * @param  RefundReasonModel $refundReasonModel               [description]
     * @return [type]                               [description]
     */
    public function getRefundReason(RefundReasonModel $refundReasonModel)
    {
        $list = $refundReasonModel->column('content');
        $resultData = [];
        $resultData['list'] = $list;
        $this->result(200, '请求成功', 200, '加载成功', $resultData);
    }
    /**
     * @xk 获取近期下单
     *
     * @method getNearOrder
     * @param  OrderModel   $orderModel                [description]
     * @return [type]       [description]
     * @Time   2021-10-29
     * @City   青岛
     * @Author xkyinzhe     <zhonghuaxinxing@sina.cn>
     */
    public function getNearOrder(SubOrderModel $subOrderModel)
    {
        $list = $subOrderModel
            ->alias('so')
            ->leftJoin('user u', 'u.user_sn = so.user_sn')
            ->where([['so.status', 'in', '1,2,3'], ['so.pay_status', '=', 1]])
            ->field('u.`user_name`,u.`head_pic`,so.`city`')
            ->withAttr('head_pic', function ($value, $data) {
                return getShowUrl($value);
            })
            ->select()
            ->toArray();
        $resultData = [];
        $resultData['list'] = $list;
        $this->result(200, '请求成功', 200, '加载成功', $resultData);
    }
    /**
     * @xk 获取物流公司
     *
     * @method getShippingList
     * @param  ShippingModel   $ShippingModel             [description]
     * @return [type]          [description]
     * @Time   2021-11-03
     * @City   青岛
     * @Author xkyinzhe        <zhonghuaxinxing@sina.cn>
     */
    public function getShippingList(ShippingModel $ShippingModel)
    {
        $shipping_list = $ShippingModel
            ->field('`en_name`,GROUP_CONCAT(`company_name`) as company_name_arr,GROUP_CONCAT(`company_code`) as company_code_arr')
            ->withAttr('company_name_arr', function ($value, $data) {
                if ($value) {
                    return explode(',', $value);
                }
            })
            ->withAttr('company_code_arr', function ($value, $data) {
                if ($value) {
                    return explode(',', $value);
                }
            })
            ->group('en_name')
            ->select()
            ->toArray();
        $right_list = array_column($shipping_list, 'en_name');
        // $right_list = [];
        $this->result(200, '请求成功', 200, '加载成功', ['list' => $shipping_list, 'right_list' => $right_list]);
    }
}
